package servlet;

import cn.hutool.json.JSONUtil;
import dao.AdminDAO;
import dao.UserDAO1;
import entity.Admin;
import entity.PageBean;
import entity.Product;
import entity.User;
import redis.clients.jedis.ShardedJedis;
import util.RSAUtil;
import util.RedisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@WebServlet(name = "userLogin", value = "/product/login")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置post请求参数乱码问题
        req.setCharacterEncoding("UTF-8");
        //获得表单的请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        // 从redis中获取公钥和私钥
        ShardedJedis jedis = RedisUtil.getJedis();  //获取redis连接
        // 获取对应用户名的私钥
        String privateKey = jedis.get(username + "_privateKey");
        System.out.println("私钥：" + privateKey);
        jedis.close();
        // 使用私钥解密密码
        try {
            String decrypt = RSAUtil.decrypt(password, RSAUtil.getPrivateKey(privateKey));
            System.out.println("解密后的密码：" + decrypt);
            password = decrypt;
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserDAO1 dao = new UserDAO1();
        User user = dao.findByName(username);
        if (user!=null&&username.equals(user.getUsername()) && password.equals(user.getPassword())) {
            if (!Objects.equals(user.getUsername(), "admin")){
                resp.sendRedirect("/Mall/product/search");
            }
            // 重定向到产品列表页面
            else {
                resp.sendRedirect("/Mall/product/list");
            }
            System.out.println("成功");
        } else {
            System.out.println("登录失败");
//            jsonStr = null;
            req.getRequestDispatcher("/default.jsp").forward(req, resp);
        }

    }
}
